<template>
  <el-container class="chat-page im-container">
    <el-aside :width="asideWidth + 'px'" class="aside">
      <div class="header">
        <el-input class="search-text" size="small" placeholder="搜索" v-model="searchText">
          <template #prefix>
            <i class="fas fa-search"></i>
          </template>
        </el-input>
      </div>
      <!-- 骨架屏加载状态 - 初次加载或重新连接时显示 -->
      <div class="chat-skeleton" v-if="shouldShowSkeleton">
        <div class="skeleton-header">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-line skeleton-name"></div>
            <div class="skeleton-line skeleton-message"></div>
          </div>
          <div class="skeleton-time"></div>
        </div>
        <div class="skeleton-header">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-line skeleton-name"></div>
            <div class="skeleton-line skeleton-message"></div>
          </div>
          <div class="skeleton-time"></div>
        </div>
        <div class="skeleton-header">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-line skeleton-name"></div>
            <div class="skeleton-line skeleton-message"></div>
          </div>
          <div class="skeleton-time"></div>
        </div>
        <div class="loading-indicator">
          <i class="fas fa-spinner fa-spin"></i>
          <span>{{ isReconnecting ? '正在重新连接...' : '正在加载会话...' }}</span>
        </div>
      </div>

      <!-- 会话列表 -->
      <el-scrollbar class="chat-items" v-else-if="chatStore.chats && chatStore.chats.length > 0">
        <div v-for="(chat, index) in chatStore.chats" :key="chat.id || index">
          <chat-item v-show="!chat.delete && chat.showName && chat.showName.includes(searchText)" :chat="chat"
            :index="index" @click.native="onActiveItem(index)" @delete="onDelItem(index)" @top="onTop(index)"
            @dnd="onDnd(chat)" :active="chat === chatStore.activeChat"></chat-item>
        </div>
      </el-scrollbar>

      <!-- 空状态 - 只有在确认用户真的没有会话时才显示 -->
      <div v-else-if="shouldShowEmptyState" class="empty-chat-list">
        <div class="empty-content">
          <i class="fas fa-comments empty-icon"></i>
          <h3 class="empty-title">暂无聊天会话</h3>
          <p class="empty-desc">开始与好友或群组聊天，会话记录将显示在这里</p>
          <div class="empty-actions">
            <el-button type="primary" @click="goToFriends" class="action-btn">
              <i class="fas fa-user-friends"></i>
              查看好友
            </el-button>
            <el-button @click="goToGroups" class="action-btn">
              <i class="fas fa-users"></i>
              查看群聊
            </el-button>
          </div>
        </div>
      </div>

      <!-- 水平拉伸分隔器 -->
      <resizable-divider direction="horizontal" :min-width="200" :max-width="400" @resize="handleAsideResize" />
    </el-aside>
    <el-container>
      <chat-box v-if="chatStore.activeChat" :chat="chatStore.activeChat" @update-chat-last-message="handleUpdateChatLastMessage"></chat-box>
      <div v-else class="content-empty-state">
        <i class="welcome-icon fas fa-comments"></i>
        <h3 class="welcome-title">选择一个聊天开始对话</h3>
        <p class="welcome-desc">从左侧选择一个好友或群聊，开始愉快的聊天吧！</p>
      </div>
    </el-container>
  </el-container>
</template>

<script>
import ChatItem from "@/components/IMChat/ChatItem.vue";
import ChatBox from "@/components/IMChat/ChatBox.vue";
import ResizableDivider from "@/components/common/ResizableDivider.vue";
import { setFriendDndApi } from '@/api/imFriend.js';
import { setGroupDndApi } from '@/api/imGroup.js';
import { getAsideWidth, saveAsideWidth, debounce } from "@/utils/im/layoutPreferences.js";

export default {
  name: "IMChat",
  components: {
    ChatItem,
    ChatBox,
    ResizableDivider
  },
  data() {
    return {
      searchText: "",
      messageContent: "",
      group: {},
      groupMembers: [],
      asideWidth: getAsideWidth('chat'), // 侧边栏宽度，从本地存储恢复
      isInitialLoading: true, // 初始加载状态
      loadingTimer: null, // 加载定时器
      hasEverHadChats: false, // 是否曾经有过会话记录
      isReconnecting: false // 是否正在重新连接
    }
  },
  methods: {
    // 处理侧边栏拉伸
    handleAsideResize(size) {
      if (size.width) {
        this.asideWidth = size.width;
        // 防抖保存到本地存储
        this.debouncedSaveAsideWidth(size.width);
      }
    },
    onActiveItem(index) {
      this.chatStore.setActiveChat(index);
    },
    onDelItem(index) {
      this.chatStore.removeChat(index);
    },
    /**
     * 手动置顶会话
     * 注意：手动置顶不更新会话时间，保持原有的最后聊天时间
     */
    onTop(chatIdx) {
      // 第二个参数为false，表示不更新会话时间
      this.chatStore.moveTop(chatIdx, false);
    },
    onDnd(chat) {
      if (chat.type == 'PRIVATE') {
        this.setFriendDnd(chat, chat.targetId, !chat.isDnd)
      } else {
        this.setGroupDnd(chat, chat.targetId, !chat.isDnd)
      }
    },
    setFriendDnd(chat, friendId, isDnd) {
      setFriendDndApi({ friendId, isDnd }).then(() => {
        this.friendStore.setDnd(friendId, isDnd)
        this.chatStore.setDnd(chat, isDnd)
      }).catch((error) => {
        this.$message.error("设置免打扰失败：" + (error.message || "未知错误"));
      })
    },
    setGroupDnd(chat, groupId, isDnd) {
      setGroupDndApi({ groupId, isDnd }).then(() => {
        this.groupStore.setDnd(groupId, isDnd)
        this.chatStore.setDnd(chat, isDnd)
      }).catch((error) => {
        this.$message.error("设置免打扰失败：" + (error.message || "未知错误"));
      })
    },

    /**
     * 跳转到好友页面
     */
    goToFriends() {
      this.$router.push('/im/friend');
    },

    /**
     * 跳转到群聊页面
     */
    goToGroups() {
      this.$router.push('/im/group');
    },

    /**
     * 初始化加载状态管理
     */
    initLoadingState() {
      // 检查本地存储是否有会话记录的痕迹
      this.checkLocalChatHistory();

      // 设置最小加载时间，避免闪烁
      this.loadingTimer = setTimeout(() => {
        this.isInitialLoading = false;
        this.isReconnecting = false;
      }, 2000); // 增加到2秒，给连接更多时间

      // 监听聊天数据变化
      this.$watch(() => this.chatStore.chats, (newChats, oldChats) => {
        if (newChats && newChats.length > 0) {
          // 记录用户曾经有过会话
          this.hasEverHadChats = true;
          this.saveLocalChatHistory();

          // 有数据时立即停止加载
          if (this.loadingTimer) {
            clearTimeout(this.loadingTimer);
            this.loadingTimer = null;
          }
          this.isInitialLoading = false;
          this.isReconnecting = false;
        }
      }, { immediate: true });
    },

    /**
     * 获取当前用户的会话历史记录键名
     */
    getChatHistoryKey() {
      const userId = this.userStore.userInfo?.id || 'anonymous';
      return `im_chat_history_exists_${userId}`;
    },

    /**
     * 检查本地存储的会话历史记录（按用户区分）
     */
    checkLocalChatHistory() {
      try {
        const historyKey = this.getChatHistoryKey();
        const hasHistory = localStorage.getItem(historyKey);
        if (hasHistory === 'true') {
          this.hasEverHadChats = true;
          // 如果本地记录显示用户有会话历史，则认为是重新连接
          this.isReconnecting = true;
        }
      } catch (error) {
        console.warn('检查本地会话历史失败:', error);
      }
    },

    /**
     * 保存会话历史记录标记到本地存储（按用户区分）
     */
    saveLocalChatHistory() {
      try {
        const historyKey = this.getChatHistoryKey();
        localStorage.setItem(historyKey, 'true');
      } catch (error) {
        console.warn('保存会话历史标记失败:', error);
      }
    },

    /**
     * 清除会话历史记录标记（用于测试或重置）
     */
    clearLocalChatHistory() {
      try {
        const historyKey = this.getChatHistoryKey();
        localStorage.removeItem(historyKey);
        this.hasEverHadChats = false;
      } catch (error) {
        console.warn('清除会话历史标记失败:', error);
      }
    },

    /**
     * 处理页面重新激活（从其他页面返回）
     */
    handlePageReactivation() {
      // 检查是否有历史记录
      this.checkLocalChatHistory();

      // 如果有历史记录但当前无会话，说明需要重新连接
      if (this.hasEverHadChats && (!this.chatStore.chats || this.chatStore.chats.length === 0)) {
        this.isReconnecting = true;
        this.isInitialLoading = true;

        // 重新设置加载定时器
        if (this.loadingTimer) {
          clearTimeout(this.loadingTimer);
        }

        this.loadingTimer = setTimeout(() => {
          this.isInitialLoading = false;
          this.isReconnecting = false;
        }, 3000); // 重连时给更多时间
      }
    },

    /**
     * 处理会话列表最后消息更新
     */
    handleUpdateChatLastMessage(data) {
      const { chatId, lastContent, lastSendTime } = data;

      // 查找对应的会话并更新
      const chat = this.chatStore.chats.find(c => c.id === chatId);
      if (chat) {
        chat.lastContent = lastContent;
        chat.lastSendTime = lastSendTime;

        // 触发会话列表重新排序（最新消息的会话排到最前面）
        this.chatStore.sortChats();
      }
    }
  },
  computed: {
    loading() {
      return this.chatStore.loadingGroupMsg || this.chatStore.loadingPrivateMsg
    },

    /**
     * 是否应该显示骨架屏
     * 条件：初次加载 或者 (曾经有过会话且当前无会话，表示重新连接中)
     */
    shouldShowSkeleton() {
      return this.isInitialLoading ||
             (this.hasEverHadChats && (!this.chatStore.chats || this.chatStore.chats.length === 0));
    },

    /**
     * 是否应该显示空状态
     * 条件：不在加载中 且 从未有过会话记录 且 当前确实无会话
     */
    shouldShowEmptyState() {
      return !this.isInitialLoading &&
             !this.hasEverHadChats &&
             (!this.chatStore.chats || this.chatStore.chats.length === 0);
    }
  },
  mounted() {
    // 初始化防抖保存函数
    this.debouncedSaveAsideWidth = debounce((width) => {
      saveAsideWidth('chat', width);
    }, 300);

    // 初始化加载状态
    this.initLoadingState();
  },

  activated() {
    // Vue keep-alive 激活时处理重连
    console.log("聊天页面被激活，检查重连状态...");
    this.handlePageReactivation();
  },

  beforeDestroy() {
    // 清理定时器
    if (this.loadingTimer) {
      clearTimeout(this.loadingTimer);
      this.loadingTimer = null;
    }
  }
}
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

.chat-page {
  height: 100%;
  width: 100%;
  overflow: hidden; // 隐藏所有滚动条，防止页面出现左右滑动条
  box-sizing: border-box; // 确保边框和内边距不会导致溢出

  .aside {
    display: flex;
    flex-direction: column;
    background: var(--im-bg-secondary);
    border-right: var(--im-border);
    height: 100%;
    position: relative;

    .header {
      height: 60px;
      display: flex;
      align-items: center;
      padding: var(--im-spacing-lg);
      border-bottom: var(--im-border);
      background: var(--im-bg-primary);
      position: relative;

      // 添加微妙的阴影
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 1px;
        background: linear-gradient(90deg, transparent, var(--im-border-color-light), transparent);
      }

      .search-text {
        width: 100%;

        :deep(.el-input__wrapper) {
          border-radius: var(--im-border-radius-lg);
          border: var(--im-border);
          background: var(--im-bg-tertiary);
          transition: all var(--im-transition-base);

          &:hover {
            border-color: var(--im-color-primary);
          }

          &.is-focus {
            border-color: var(--im-color-primary);
            box-shadow: 0 0 0 2px rgba(var(--im-color-primary-rgb), 0.1);
          }
        }

        :deep(.el-input__prefix) {
          color: var(--im-text-color-secondary);
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
        }

        :deep(.el-input__inner) {
          color: var(--im-text-color-primary);
          background: transparent;

          &::placeholder {
            color: var(--im-text-color-placeholder);
          }
        }
      }
    }

    .chat-loading {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--im-bg-primary);
    }

    .chat-items {
      flex: 1;
      background: var(--im-bg-primary);
      padding: var(--im-spacing-sm) 0;

      // 隐藏水平滚动条
      :deep(.el-scrollbar__wrap) {
        overflow-x: hidden !important;
        padding-right: 2px; // 为滚动条留出空间
      }

      :deep(.el-scrollbar__bar.is-horizontal) {
        display: none !important;
      }

      // 自定义滚动条样式
      :deep(.el-scrollbar__bar.is-vertical) {
        .el-scrollbar__thumb {
          background-color: rgba(var(--im-color-primary-rgb), 0.3);
          border-radius: 4px;
          transition: all var(--im-transition-base);

          &:hover {
            background-color: rgba(var(--im-color-primary-rgb), 0.5);
          }
        }
      }

      // 会话列表容器
      >div {
        position: relative;
        margin-bottom: var(--im-spacing-xs);

        // 移除分隔线，因为新的卡片式设计不需要
        &:not(:last-child)::after {
          display: none;
        }

        // 最后一个元素的底部间距
        &:last-child {
          margin-bottom: var(--im-spacing-lg);
        }
      }
    }

    // 骨架屏加载样式
    .chat-skeleton {
      flex: 1;
      background: var(--im-bg-primary);
      padding: var(--im-spacing-base);

      .skeleton-header {
        display: flex;
        align-items: center;
        padding: var(--im-spacing-lg);
        margin-bottom: var(--im-spacing-sm);
        border-radius: var(--im-border-radius-lg);
        background: var(--im-bg-secondary);

        .skeleton-avatar {
          width: 44px;
          height: 44px;
          border-radius: 50%;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
          flex-shrink: 0;
        }

        .skeleton-content {
          flex: 1;
          margin-left: var(--im-spacing-lg);

          .skeleton-line {
            height: 12px;
            border-radius: 6px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            margin-bottom: var(--im-spacing-xs);

            &.skeleton-name {
              width: 60%;
            }

            &.skeleton-message {
              width: 80%;
            }
          }
        }

        .skeleton-time {
          width: 40px;
          height: 10px;
          border-radius: 5px;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
          flex-shrink: 0;
        }
      }

      .loading-indicator {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: var(--im-spacing-sm);
        padding: var(--im-spacing-xl);
        color: var(--im-color-primary);
        font-size: var(--im-font-size-sm);

        i {
          font-size: 16px;
          animation: spin 1s linear infinite;
        }
      }
    }

    // 空状态样式
    .empty-chat-list {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--im-bg-primary);

      .empty-content {
        text-align: center;
        max-width: 300px;
        padding: var(--im-spacing-xl);

        .empty-icon {
          font-size: 64px;
          color: var(--im-color-primary);
          margin-bottom: var(--im-spacing-lg);
          opacity: 0.6;
        }

        .empty-title {
          color: var(--im-text-color-primary);
          font-size: var(--im-font-size-lg);
          font-weight: 600;
          margin: 0 0 var(--im-spacing-sm) 0;
        }

        .empty-desc {
          color: var(--im-text-color-secondary);
          font-size: var(--im-font-size-base);
          margin: 0 0 var(--im-spacing-xl) 0;
          line-height: 1.5;
        }

        .empty-actions {
          display: flex;
          gap: var(--im-spacing-sm);
          justify-content: center;

          .action-btn {
            border-radius: var(--im-border-radius-base);
            padding: var(--im-spacing-sm) var(--im-spacing-lg);
            font-size: var(--im-font-size-sm);
            transition: all var(--im-transition-base);

            &:hover {
              transform: translateY(-1px);
              box-shadow: var(--im-box-shadow-hover);
            }

            i {
              margin-right: var(--im-spacing-xs);
            }
          }
        }
      }
    }
  }

  .content-empty-state {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--im-spacing-xl);
    background: var(--im-bg-primary);
    text-align: center;

    .welcome-icon {
      font-size: 64px;
      color: var(--im-color-primary);
      margin-bottom: var(--im-spacing-lg);
      opacity: 0.8;
    }

    .welcome-title {
      color: var(--im-text-color-primary);
      font-size: var(--im-font-size-lg);
      font-weight: 600;
      margin: 0 0 var(--im-spacing-base) 0;
    }

    .welcome-desc {
      color: var(--im-text-color-secondary);
      font-size: var(--im-font-size-base);
      margin: 0;
      line-height: 1.5;
    }
  }
}

// 深色模式下的骨架屏适配
:root[data-theme='dark'] {
  .chat-page {
    .chat-skeleton {
      .skeleton-header {
        background: var(--im-bg-tertiary);

        .skeleton-avatar,
        .skeleton-line,
        .skeleton-time {
          background: linear-gradient(90deg, #2a2a2a 25%, #3a3a3a 50%, #2a2a2a 75%);
          background-size: 200% 100%;
        }
      }
    }
  }
}

// 动画定义
@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
